/*! ******************************************************************************
 *
 * Created on 2022年3月25日
 *
 * Copyright(c) YuZhou Big Data Laboratory CO.,Ltd, 2022.  All rights reserved.
 *
 *******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/

package org.yzbdl.lanius.core.metastore;

import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.common.collect.Maps;

import cn.hutool.db.Entity;
import cn.hutool.db.sql.Wrapper;

/**
 * @author hs@yzbdl.ac.cn
 *
 */
public class UpperCaseWrapper extends Wrapper {

    @Override
    public String wrap(String field) {
        String wrapedField = super.wrap(field);
        return wrapedField.toUpperCase();
    }

    @Override
    public Entity wrap(Entity entity) {
        if (null == entity) {
            return null;
        }

        final Entity wrapedEntity = new Entity();

        // wrap table name
        wrapedEntity.setTableName(wrap(entity.getTableName()));

        // wrap fields
        for (Entry<String, Object> entry : entity.entrySet()) {
            wrapedEntity.set(wrap(entry.getKey()), entry.getValue());
        }

        return wrapedEntity;
    }

    public String formatSql(String sql) {
        sql = switchCase(sql);
        return sql;
    }

    private String switchCase(String sql) {
        Pattern pattern = Pattern.compile("\'(.*?)\'");
        Matcher m = pattern.matcher(sql);

        Map<String, String> quoteStrMap = Maps.newHashMap();
        int index = 0;
        while (m.find()) {
            quoteStrMap.put("?" + index, m.group());
            sql = sql.replace(m.group(), "?" + index);
            index++;
        }

        // 转换大小写
        sql = sql.toUpperCase();

        for (Entry<String, String> entry : quoteStrMap.entrySet()) {
            sql = sql.replace(entry.getKey(), entry.getValue());
        }
        return sql;
    }

}
